<template>
	<view style="height: 100%;">
		<navi-shell title="添加博客"></navi-shell>
		<view v-if="isLogin" class="wrapper">
			<view class="head-container">
				<view class="category-container" @tap="tapSwitchCategories">
					<text class="txt-category">{{category}}</text>
					<text
						:class="showCategories?'iconfont icon-arrow-up-filling ic-drop':'iconfont icon-arrow-down-filling ic-drop'"></text>
				</view>
				<view class="space-holder"></view>
				<image src="/static/icons/commit.png" class="img-commit" @tap="tapCommit"></image>
			</view>
			<view v-if="showCategories" class="category-list-container">
				<view class="category-mask" @tap="tapHideCategories"></view>
				<view class="category-list">
					<text v-for="(item,index) in categories" :key="item.id" class="category-item"
						@tap="tapCategory(item)">
						{{item.name}}
					</text>
				</view>
			</view>
			<view class="body-container">
				<view class="title-container">
					<view class="origin-container" @tap="tapSwitchType">
						<text class="origin-name">{{originName}}</text>
						<text
							:class="showTypes?'iconfont icon-arrow-up-filling ic-origin-arr':'iconfont icon-arrow-down-filling ic-origin-arr'"></text>
					</view>
					<input type="text" class="edt-title" placeholder="标题" placeholder-class="txt-holder"
						@input="inputGetTitle" />
				</view>
				<view v-if="showTypes" class="origin-list-container">
					<text class="origin-item" v-for="(item,index) in originTypes" :key="item"
						@tap="tapOrigin(index)">{{item}}</text>
				</view>
				<view class="tags-wrapper">
					<view class="tags-container">
						<text class="tags-count-label">{{tagLabel}}</text>
						<view class="tags-input-container">
							<input type="text" :value="tagNames" v-model="tagNames" placeholder="输入或选择标签,标签间使用逗号隔开"
								class="edt-tags" @focus="focusShowTags" @blur="blurCountTags" @input="inputGetTags"
								placeholder-class="txt-holder" />
							<text @tap="tapHideTags"
								:class="showTags?'iconfont icon-arrow-up-filling ic-tag-drop':'iconfont icon-arrow-down-filling ic-tag-drop'"></text>
						</view>
					</view>
					<view v-if="showTags" class="tags-drop-wrapper">
						<view class="view-holder"></view>
						<!-- 占位符，标签选择框会收缩，使用占位符与文本保持统一宽度 -->
						<view class="tags-drop-container">
							<text class="btn-clear-container">
								<text v-if="tagNames.length>0" @tap="tapClearTags" class="btn-clear-close">清空</text>
								<text v-for="(item,index) in tags" :key="item.id" @tap="tapTag(item)"
									class="tag-item">{{item.name}}</text>
								<text class="btn-clear-close" @tap="tapHideTags">收起</text>
							</text>
						</view>
					</view>
				</view>
				<view class="upload-pic-container" @tap="tapChooseImage">
					<image src="../../static/icons/ic_publish.png" mode="aspectFill" class="pic"></image>
					<text class="txt-holder">{{picName}}</text>
				</view>
				<image v-if="showPicture" :src="picUrl" mode="aspectFill" class="pic-hot" @tap="showPicture=false">
				</image>
				<rich-editor :showTabBar="true" :uploadImageUrl="this.$params.host+this.$params.action_upload"
					class="editor" @input="inputGetContent"></rich-editor>
			</view>
			<checkbox-group class="check-group" @change="changeCheck">
				<label class="option-label" v-for="(option,index) in options" :key="option">
					<checkbox :value="index + ''" /><text>{{option}}</text>
				</label>
			</checkbox-group>
		</view>
		<login-dialog ref="login" @after="afterLogin"></login-dialog>
	</view>
</template>

<script>
	const app = getApp()
	let categoryId = ''
	let originType = 0
	let title = ''
	let content = ''
	let rights = [false, false, false, false]
	let tagIds = []
	let delta=1
	export default {
		data() {
			return {
				isLogin: false,
				categories: [],
				showCategories: false,
				category: '请选择类型',
				showTypes: false,
				originName: '原创',
				originTypes: ['原创', '转载', '翻译'],
				showTags: false,
				tagLabel: '标签[0]',
				tagNames: '',
				tags: [],
				picName: '请点击选择焦点图片',
				picUrl: '',
				showPicture: false,
				options: ['转载', '评论', '打赏', '推荐']
			}
		},
		mounted() {
			this.isLogin = app.globalData.token.length > 0
			if (!this.isLogin) {
				delta=2
				this.$refs.login.show()
			}
		},
		onLoad() {
			if (this.isLogin) {
				this.afterLogin()
			}
		},
		methods: {
			afterLogin() {
				this.isLogin = app.globalData.token.length > 0
				if (this.isLogin) {
					this.getCategories()
					this.getTags()
				}
			},
			getTags() {
				let tags = uni.getStorageSync('tags')
				if (tags) {
					this.tags = tags
				}
				let url = this.$params.host + this.$params.action_tags
				this.$request.get(url, res => {
					this.tags = res.data.data
					uni.setStorageSync('tags', this.tags)
				})
			},
			focusShowTags() {
				this.showTags = true
			},
			blurCountTags() {
				let names = this.tagNames.split(',').filter(n => n.trim().length > 0)
				names = this.$utils.distinct(names)
				this.tagNames = names.toString()
				this.tagLabel = `标签[${names.length}]`
			},
			inputGetTags() {
				//如果是中文符号就换成英文符号
				if (this.tagNames.endsWith('，')) {
					this.tagNames = this.tagNames.replace("，", ",")
				}
				//去重
				let names = this.tagNames.split(',').filter(n => n.trim().length > 0)
				if (this.tagNames.endsWith(',')) {
					names = this.$utils.distinct(names)
					this.tagNames = names.toString() + ','
				}
				this.tagLabel = `标签[${names.length}]`
			},
			tapHideTags() {
				this.showTags = false
			},
			tapClearTags() {
				this.tagNames = ''
				this.tagLabel = '标签[0]'
			},
			tapTag(tag) {
				let duplicated = false
				this.tagNames.split(',').forEach(n => {
					if (n.toLowerCase() == tag.name.toLowerCase()) {
						duplicated = true
						return
					}
				})
				if (duplicated) {
					this.showTags = false
					return
				}
				if (this.tagNames.length > 0) {
					this.tagNames = `${this.tagNames},`
				}
				this.tagNames += tag.name
				this.tagLabel = `标签[${this.tagNames.split(',').length}]`
			},
			getCategories() {
				let url = this.$params.host + this.$params.action_categories
				this.$request.get(url, res => {
					this.categories = res.data.data
				})
			},
			tapSwitchCategories() {
				this.showCategories = !this.showCategories
			},
			tapHideCategories() {
				this.showCategories = false
			},
			tapCategory(category) {
				categoryId = category.id
				this.category = category.name
				this.showCategories = false
			},
			tapSwitchType() {
				this.showTypes = !this.showTypes
			},
			tapOrigin(index) {
				originType = index
				this.originName = this.originTypes[index]
				this.showTypes = false
			},
			inputGetTitle(e) {
				title = e.detail.value
			},
			tapChooseImage() {
				let url = this.$params.host + this.$params.action_upload
				uni.chooseImage({
					count: 1,
					success: res => {
						let path = res.tempFilePaths[0]
						this.$request.postFile(url, 'file', path, {}, res => {
							let json = JSON.parse(res.data)
							this.picName = json.data
							this.picUrl = this.$params.host + this.picName
							this.showPicture = true
						})
					}
				})
			},
			inputGetContent(e) {
				content = e.html
			},
			changeCheck(e) {
				rights = [false, false, false, false]
				e.detail.value.forEach(o => {
					rights[parseInt(o)] = true
				})
			},
			isLegal() {
				if (!this.$utils.checkLength(title, 6, '标题')) {
					return false
				}
				if (!this.$utils.checkLength(content, 20, '内容')) {
					return false
				}
				if (this.picName == '请点击选择焦点图片') {
					uni.showToast({
						title: '请选择图片',
						icon: 'none'
					});
					return false
				}
				if (categoryId.length == 0) {
					uni.showToast({
						title: '请点击顶部下拉列表选择类型',
						icon: 'none'
					});
					return false
				}
				if (this.tagNames.length == 0) {
					uni.showToast({
						title: '请至少添加一个标签',
						icon: 'none'
					});
					return false
				}
				return true
			},
			tapCommit() {
				if (!this.isLegal()) {
					return
				}
				uni.showModal({
					title: '确认',
					content: '确认提交',
					showCancel: true,
					cancelText: '算了',
					confirmText: '提交',
					success: res => {
						if (res.confirm) {
							this.checkTags(this.postBlog())
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			postBlog() {
				let data={
					category_id:categoryId,
					content,
					origin_value:originType,
					picture:this.picName,
					publish_now:true,
					read_count:0,
					title,
					token:app.globalData.token,
					user_id:app.globalData.uid,
					tag_ids:tagIds,
					comment:rights[1],
					reprint:rights[0],
					sponsor:rights[2],
					recommend:rights[3]
				}
				let url=this.$params.host+this.$params.action_add_blog
				this.$request.post(url,data,res=>{
					if(!res.success){
						uni.showToast({
							title:res.message,
							icon:'none'
						});
						return
					}
					if(!res.data.picture.startsWith('http')){
						res.data.picture=this.$params.host+res.data.picture
					}
					res.data.user.avatar=this.$params.host+app.globalData.avatar
					this.$noti.post(this.$params.noti_add_blog,res.data)
					uni.navigateBack({
						delta: delta
					});
				})
			},
			checkTags(fnCommit) {
				let unTags = []
				let names = this.tagNames.split(",").filter(n => n.trim().length > 0)
				names.forEach(name => {
					let old = this.tags.find(t => t.name == name)
					if (old) {
						tagIds.push(old.id)
					} else {
						unTags.push(name)
					}
				})
				if (unTags.length > 0) {
					uni.showModal({
						title: '添加标签',
						content: `要添加${unTags.toString()}作为新标签吗？`,
						showCancel: true,
						cancelText: '算了',
						confirmText: '添加',
						success: res => {
							if (res.confirm) {
								console.log("已经提交了");
								fnCommit()
							}
						},
						fail: () => {},
						complete: () => {}
					});
				} else {
					fnCommit()
				}
			}
		}
	}
</script>

<style>
	@import url("add.css");
</style>
